<?php
namespace app\reduction\controller;
use app\AdminRest;
use app\ApiRest;
use app\reduction\model\PayRecord;
use app\shop\controller\IndexWxPay;
use think\App;
use app\reduction\model\StaffRecord as StaffRecord;
use app\reduction\model\UserRecord as model;
use app\reduction\model\Company;
use app\reduction\model\Active;
use think\facade\Db;


class IndexRecord extends ApiRest
{

    protected $model;

    protected $staff_record;

    protected $company_model;

    protected $active_model;

    public function __construct(App $app) {

        parent::__construct($app);
        $this->model         = new Model();

        $this->staff_record  = new StaffRecord();

        $this->company_model = new Company();

        $this->active_model  = new Active();
        //初始化一下
        $this->model->initRecord();
    }

    /**
     * @author chenniang
     * @DataTime: 2020-04-21 15:22
     * @功能说明:用户满减列表
     */
    public function userRecordList(){

        $input = $this->_input;
        //uniacid
        $dis[] = ['uniacid','=',$this->_uniacid];
        //未使用的
        $dis[] = ['status','=',1];
        //当前用户的
        $dis[] = ['user_id','=',$this->getUserId()];
        //查询
        $data  = $this->model->userRecordList($dis);

        return $this->success($data);

    }




    /**
     * @author chenniang
     * @DataTime: 2020-04-22 10:59
     * @功能说明:用户获取券
     */
    public function getCoupon(){

        $input = $this->_input;

        $coupon= $this->active_model->activeInfo(['id'=>$input['active_id'],'status'=>1]);

        $is_staff = Db::name('longbing_card_user')->where(['id'=>$this->getUserId(),'is_staff'=>1])->find();

        if(!empty($is_staff)){

            $this->errorMsg('员工无法领取');

        }
        if(empty($coupon)){

            $this->errorMsg('获取未找到');
        }

        if($coupon['num']<=$coupon['get_num']){

            $this->errorMsg('券已领完');
        }

        //查看是否领取过该券
        $dis = [

            'active_id'=> $input['active_id'],

            'staff_id' => $input['staff_id'],

            'user_id'  => $this->getUserId(),

            'status'   => 1,
        ];

        $user_record = $this->model->recordInfo($dis);

        if(!empty($user_record)){

            $this->errorMsg('你已有此券');
        }
        //查看是否有公司限制
        if($coupon['use_condition']==1){

            $coupon_company = $this->company_model->where(['active_id'=>$input['active_id']])->column('company_id');

            $my_company     = Db::name('longbing_card_user_info')->where(['fans_id'=>$input['staff_id']])->value('company_id');

            if(!in_array($my_company,$coupon_company)){

                $this->errorMsg('该员工没有此权限');

            }

        }
        Db::startTrans();
        //添加发放记录
        $dis = [

            'staff_id' => $input['staff_id'],

            'active_id'=> $input['active_id']
        ];
        //查看有没有发放过
        $data = $this->staff_record->recordInfo($dis);

        if(empty($data)){

            $input['uniacid']  = $this->_uniacid;

            $this->staff_record->recordAdd($input,$input['staff_id']);

        }
        //领取
        $res = $this->model->addRecord($this->getUserId(),$input['staff_id'],$coupon);


        $res = $this->active_model->where(['id'=>$input['active_id'],'create_time'=>$coupon['create_time']])->update(['create_time'=>$coupon['create_time']+1]);

        if($res!=1){

            $this->errorMsg('领取人数过多,请稍后重试');

        }


        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-22 13:25
     * @功能说明:员工发放
     */
    public function addStaffRecord(){

        $input = $this->_input;

        $dis = [

            'staff_id' => $this->getUserId(),

            'active_id'=> $input['active_id']
        ];
        //查看有没有发放过
        $data = $this->staff_record->recordInfo($dis);

        if(empty($data)){

            $input['staff_id'] = $this->getUserId();

            $input['uniacid']  = $this->_uniacid;

            $this->staff_record->recordAdd($input,$this->getUserId());

        }

        return $this->success(1);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-22 16:15
     * @功能说明:员工端领取详情
     */
    public function staffRecordInfo(){

        $input = $this->_input;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.staff_id','=',$this->getUserId()];

        $dis[] = ['a.active_id','=',$input['active_id']];

        if(!empty($input['status'])){

            $dis[] = ['a.status','=',$input['status']];
        }

        $data['list'] = $this->model->recordList($dis,10);

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2020-04-22 17:08
     * @功能说明:支付
     */
    public function payOrder(){

        $input = $this->_input;
        //支付金额
        $pay_price = $input['pay_price'];
        //优惠券id
        $coupon_id = 0;
        //佣金
        $cash      = 0;
        Db::startTrans();
        //如果使用满减
        if(!empty($input['coupon_id'])){

            $coupon = $this->model->recordInfo(['id'=>$input['coupon_id']]);

            if(empty($coupon)){

                $this->errorMsg('满减券不存在');
            }

            if($coupon['status']!=1){

                $this->errorMsg('满减券已过期或已使用');

            }

            if($coupon['full']>$input['pay_price']){

                $this->errorMsg('支付金额未达到最低消费金额');
            }
            //折后金额
            $pay_price -= $coupon['reduction'];
            //优惠券id
            $coupon_id  = $input['coupon_id'];
            //佣金
            $cash       = $coupon['cash'];
            //使用
            //$this->model->recordUpdate(['id'=>$coupon_id],['status'=>2,'use_time'=>time(),'pay_price'=>$pay_price]);
        }
        //订单号
        $out_trade_no = date( 'YmdHis' ) . '0' . $this->_uniacid. '0';

        $idlen        = strlen($this->_uniacid);
        //订单编号
        $order_code   = $out_trade_no . str_repeat( '0', 11 - $idlen ) . rand(0,9999);

        $pay_price    = round($pay_price,2);

        if($pay_price<=0){

            $this->errorMsg('支付金额错误');

        }
        $insert = [

            'uniacid'    => $this->_uniacid,
            //用户id
            'user_id'    => $this->getUserId(),

            'order_code' => $order_code,

            'pay_price'  => $pay_price,

            'staff_id'   => $input['staff_id'],

            'init_price' => $input['pay_price'],

            'status'     => 0,

            'coupon_id'  => $coupon_id,

            'cash'       => $cash
        ];

        $pay_record = new PayRecord();
        //增加订单
        $pay_record->addRecord($insert);
        //增加佣金流水
        if(!empty($coupon['cash'])){
            //增加佣金流水
            $pay_record->addWater($order_code,$coupon);
        }

        Db::commit();
        //支付类
        $pay_controller = new IndexWxPay($this->app);
        //用户
        $user           = $this->getUserInfo();
        //支付
        $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$user['openid'],$this->_uniacid,"满减返佣",['type' => 'reduction' , 'out_trade_no' => $order_code],$pay_price);

        if(!empty($jsApiParameters['code'])&&$jsApiParameters['code']==-1){

            $this->errorMsg($jsApiParameters['msg']);
        }
        $re_data['pay_list'] = $jsApiParameters;

        return $this->success($re_data);

    }






}
